using System.Data.SqlClient;

namespace MsSqlSpatial.Utility
{
    public class ConnectionOptions
    {
        /// <summary>
        /// If true, the <see cref="Database"/> will be attached as a file, otherwise it will be specified as the initial catalogue
        /// </summary>
        public bool AttachAsFile;

        /// <summary>
        /// Database name.
        /// </summary>
        public string Database;

        /// <summary>
        /// Database login name. If not specified for SQL Server, 
        /// it uses Windows authentication (SSPI).
        /// </summary>
        public string Login;

        public string Password;

        /// <summary>
        /// Database server address and instance. 
        /// </summary>
        public string Server;

        /// <summary>
        /// Specifies whether the connection is to a SQL Express user instance or not
        /// </summary>
        public bool UserInstance;

        public ConnectionOptions()
        {
        }

        public ConnectionOptions(string server, string database, string login, string password)
        {
            Server = server;
            Database = database;
            Login = login;
            Password = password;
        }

        internal string GetSqlServerConnectionString()
        {
            var builder = new SqlConnectionStringBuilder();
            if (AttachAsFile)
                builder.AttachDBFilename = Database;
            else
                builder.InitialCatalog = Database;
            builder.DataSource = Server;
            builder.IntegratedSecurity = string.IsNullOrEmpty(Login);
            if (!string.IsNullOrEmpty(Login))
            {
                builder.UserID = Login;
                builder.Password = Password;
            }
            builder.UserInstance = UserInstance;
            return builder.ConnectionString;
        }

        internal string GetPostGisConnectionString()
        {
            string[] parts = Server.Split(':');
            string server = parts[0];
            string port = "5432";
            if (parts.Length > 1)
                port = parts[1];
            return string.Format("Server={0};Port={1};Database={2};User Id={3};Password={4};Encoding=UNICODE;", server,
                                 port, Database, Login, Password);
        }
    }
}